package com.andy.blog.admin.service.impl;

import com.alibaba.excel.metadata.data.HyperlinkData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.andy.blog.admin.dto.document.ExcelDataCsvDTO;
import com.andy.blog.admin.dto.document.ExcelDataDTO;
import com.andy.blog.admin.service.ExcelBusService;
import com.andy.blog.common.utils.DateUtils;
import com.google.common.collect.Lists;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by andy on 2023-05-01 11:02
 */
@Service
public class ExcelBusServiceImpl implements ExcelBusService {

    @Override
    public Tuple2<List<List<String>>, List<ExcelDataCsvDTO>> exportCsv() {
        // head
        List<List<String>> headList = Lists.newArrayList();
        List<String> head0 = Lists.newArrayList();
        head0.add("数字");
        List<String> head1 = Lists.newArrayList();
        head1.add("字符串");
        List<String> head2 = Lists.newArrayList();
        head2.add("日期");
        headList.add(head0);
        headList.add(head1);
        headList.add(head2);

        // 数据
        List<ExcelDataCsvDTO> excelDataCsvDTOS = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            excelDataCsvDTOS.add(ExcelDataCsvDTO.builder()
                    .id((long) i)
                    .msg("字符串" + i)
                    .date(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS) + "\t")
                    .build());
        }
        return Tuple.of(headList, excelDataCsvDTOS);
    }

    @Override
    public List<ExcelDataDTO> exportExcel() {
        List<ExcelDataDTO> list = new ArrayList<>();
        ExcelDataDTO excelDataDTO = new ExcelDataDTO();
        try {
            URL url = new URL("http://img.netbian.com/file/20150603/f0b37f11b835ff964ec89f32873acbb0.jpg");

            URLConnection urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(2000);
            urlConnection.setReadTimeout(6000);
            InputStream inputStream = urlConnection.getInputStream();
            excelDataDTO.setInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置超链接
        WriteCellData<String> hyperlink = new WriteCellData<>("官方网站");
        excelDataDTO.setHyperlink(hyperlink);
        HyperlinkData hyperlinkData = new HyperlinkData();
        hyperlink.setHyperlinkData(hyperlinkData);
        hyperlinkData.setAddress("https://www.baidu.com/");
        hyperlinkData.setHyperlinkType(HyperlinkData.HyperlinkType.URL);

        list.add(excelDataDTO);

        return list;
    }
}
